// agent.go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/mem"
)

type SystemInfo struct {
	CPUUsage    float64 `json:"cpu_usage"`
	MemoryUsage float64 `json:"memory_usage"`
	// 可以根据需求添加其他字段
}

func collectSystemInfo() SystemInfo {
	cpuUsage, err := cpu.Percent(time.Second, false)
	if err != nil {
		log.Fatal(err)
	}

	memory, err := mem.VirtualMemory()
	if err != nil {
		log.Fatal(err)
	}

	// 在这里可以添加其他信息的采集

	return SystemInfo{
		CPUUsage:    cpuUsage[0],
		MemoryUsage: memory.UsedPercent,
		// 可以根据需求添加其他字段
	}
}

func main() {
	serverURL := "http://localhost:8080/system-info"

	for {
		info := collectSystemInfo()

		// 发送信息到 Server
		err := sendSystemInfo(serverURL, info)
		if err != nil {
			log.Printf("Failed to send data to server: %v", err)
		} else {
			log.Println("System info sent successfully")
		}

		time.Sleep(5 * time.Second) // 每 5 秒发送一次
	}
}

func sendSystemInfo(url string, info SystemInfo) error {
	data, err := json.Marshal(info)
	if err != nil {
		return err
	}

	resp, err := http.Post(url, "application/json", bytes.NewBuffer(data))
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
	}

	return nil
}
